<template>
  <div class="device-tree-table">
    <!-- 顶部搜索 -->
    <SearchFilters v-model="flatList" />

    <!-- 树形表格（一个表） -->
    <el-table
      :data="treeRows"
      row-key="id"
      :tree-props="{ children: 'children' }"
      border
      height="600"
      style="width: 100%"
    >
      <el-table-column prop="name" label="设备名称" min-width="250" />

      <el-table-column prop="code" label="编码" width="180" />

      <el-table-column prop="nodeType" label="类型" width="110">
        <template #default="{ row }">
          <el-tag size="small" :type="tagType(row.nodeType)">
            {{ row.nodeType }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button type="primary" link size="small" @click="openEditDevice(row)">
            评估等级
          </el-button> 
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="tree-pagination" v-if="totalRoots > pageSize">
      <el-pagination
        background
        layout="total, prev, pager, next, jumper, sizes"
        :total="totalRoots"
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[5,10,20,50]"
        @current-change="noop"
        @size-change="handleSizeChange"
      />
    </div>
  </div>

  <AssessmentDialog ref="dlg" @refresh="getList" />
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import SearchFilters from './SearchFilters.vue'
import AssessmentDialog from "@/components/sbtz/assessment/AssessmentDialog.vue";
import { listAssessment } from "@/api/sbtz/assessment";

const flatList = ref([]) // SearchFilters 返回的扁平 rows
const allRoots = ref([])

const pageNum = ref(1)
const pageSize = ref(10)
const totalRoots = ref(0)
const dlg = ref(null);
const list = ref([]);

/** 监听搜索结果，重建树结构 */
watch(flatList, (rows) => {
  if (!rows?.length) {
    allRoots.value = []
    totalRoots.value = 0
    return
  }
  const filtered = rows.filter(r => r.nodeType !== 'SYSTEM')

  const map = new Map()
  filtered.forEach(f => map.set(f.id, { ...f, children: [] }))
  const roots = []
  filtered.forEach(f => {
    const cur = map.get(f.id)
    if (!f.parentId || !map.has(f.parentId)) roots.push(cur)
    else map.get(f.parentId).children.push(cur)
  })
  roots.forEach(d => attachMockSpares(d))
  allRoots.value = roots
  totalRoots.value = roots.length
  pageNum.value = 1
})

function getList() {
  // 如需刷新外层评估列表，保留；不需要可删
  listAssessment().then((res) => (list.value = res.rows));
}
/** 当前页数据 */
const treeRows = computed(() => {
  const start = (pageNum.value - 1) * pageSize.value
  const end = start + pageSize.value
  return allRoots.value.slice(start, end)
})

/** 模拟备件 */
function attachMockSpares(node) {
  // 如果当前节点是备件，就不要继续递归
  if (node.nodeType === 'SPARE') return

  node.children = node.children || []

  node.spareInfos = [
    { id: node.id + '-s1', name: '传感器', nodeType: 'SPARE', code: 'SP001' },
    { id: node.id + '-s2', name: '电机', nodeType: 'SPARE', code: 'SP002' }
  ]

  // 把备件挂到当前节点的 children
  node.children.push(...node.spareInfos)

  // ✅ 只递归真正的子设备（不是备件）
  node.children.forEach(child => {
    if (child.nodeType !== 'SPARE') attachMockSpares(child)
  })
}


/** 颜色 */
function tagType(type) {
  return {
    MACHINE: 'primary',
    MODULE: 'success',
    COMPONENT: 'warning',
    PART: 'info',
    SPARE: 'danger'
  }[type] || 'default'
}

/** 操作按钮 */
 
function openEditDevice(node) {
  dlg.value.open(node); // 弹出当前组件自己的修改窗口
}
function openAddAssessment(row) {
  console.log('新增评估', row)
}

function handleSizeChange() { pageNum.value = 1 }
function noop() {}
</script>

<style scoped>
.device-tree-table {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 10px 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.tree-pagination {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>
